package com.yima.baseproj.module.app.dict.dict;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yima.baseproj.module.app.dict.data.AppDictDataEntity;
import com.yima.baseproj.module.app.dict.data.AppDictDataService;
import com.yima.baseproj.module.app.dict.dict.model.AppDictAddParamModel;
import com.yima.baseproj.module.app.dict.dict.model.AppDictEditParamModel;
import com.yima.baseproj.module.app.dict.dict.model.AppDictSearchModel;
import com.yima.baseproj.config.exception.type.ApiException;
import com.yima.baseproj.module.config.BaseController;
import com.yima.baseproj.module.config.utils.PageUtil;
import com.yima.baseproj.module.config.utils.PageVo;
import com.yima.baseproj.security.SecurityUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author 一码
 * @createDate 2023/4/1 09:00
 * @contact 1424529270@qq.com
 */
@Api(tags = "字典管理")
@RestController
@RequestMapping("/api/app/dict")
public class AppDictController extends BaseController {

    @Resource
    private AppDictService appDictService;

    @Resource
    private AppDictDataService appDictDataService;

    /**
     *
     * 搜索
     * @return
     */

    @ApiOperation("查询分页")
    @GetMapping("/findAllByPage")
    public Object findAllByPage(PageVo page, AppDictSearchModel searchVo) {
        Page<Map> pageData = appDictService.findByPage(PageUtil.initMpPage(page),searchVo);
        return pageData;
    }

    /**
     *
     * 搜索
     * @return
     */
    @ApiOperation("查询列表")
    @GetMapping("/findAllByList")
    public Object findAllByList(AppDictSearchModel searchVo) {
        String userId = SecurityUtil.getUserId();
        searchVo.setUserId(userId);
        List<Map> list = appDictService.findByList(searchVo);
        return list;
    }

    /**
     *
     * 前端所有数据
     * @return
     */
    @ApiOperation("前端数据列表")
    @GetMapping("/weapp/findAllByList")
    public Object weappFindAllByList() {
        List<AppDictEntity> dictEntityList = appDictService.findAllByStateIsTrue();
        List<AppDictDataEntity> dictDataEntityList = appDictDataService.list();

        List<Map> list = CollectionUtil.newArrayList();
        for (AppDictEntity appDictEntity : dictEntityList) {
            Map map = MapUtil.builder().put("type",appDictEntity.getType())
                    .put("name",appDictEntity.getName())
                    .put("dataList",dictDataEntityList.stream().filter(item->item.getDictId().equals(appDictEntity.getId())).map(item->{
                        return MapUtil.builder().put("name",item.getName())
                                .put("type",item.getType())
                                .put("isDefault",item.getIsDefault())
                                .put("sort",item.getSort()).build();
                    }).collect(Collectors.toList())).build();
            list.add(map);
        }
        return list;
    }

    /**
     *
     * 通过标识查询
     * @return
     */
    @ApiOperation("查询通过标识")
    @GetMapping("/findByType/{type}")
    public Object findByType(@PathVariable @NotBlank(message = "参数不能为空")String type) {
        AppDictEntity appDictEntity = appDictService.findByTypeAndStateIsTrue(type);
        List<AppDictDataEntity> dictDataEntityList = appDictDataService.findAllByDictId(appDictEntity.getId());

        Map map = MapUtil.builder().put("type",appDictEntity.getType())
                .put("name",appDictEntity.getName())
                .put("dataList",dictDataEntityList.stream().map(item->{
                    return MapUtil.builder()
                            .put("name",item.getName())
                            .put("type",AppDictUtil.getInstance().getDictDataName(item.getType()))
                            .put("isDefault",item.getIsDefault())
                            .put("listClass",item.getListClass())
                            .put("sort",item.getSort()).build();
                }).collect(Collectors.toList())).build();
        return map;
    }

    /**
     * 通过id查询
     * @return
     */
    @ApiOperation("查询详情")
    @GetMapping("/findById/{id}")
    public Map findById(@PathVariable @NotBlank(message = "参数不能为空")String id) {
        AppDictEntity appDictEntity = appDictService.getById(id);
        if(appDictEntity == null){
            throw ApiException.getInstance("数据不存在，请刷新重试");
        }

        Map result = JSON.parseObject(JSON.toJSONString(appDictEntity),Map.class);

        return result;
    }

    /**
     * 添加
     * @param
     * @return
     */
    @ApiOperation("添加")
    @PostMapping("/add")
    public void add(@Validated @RequestBody AppDictAddParamModel paramModel) {
        AppDictEntity dictIdAndType = appDictService.findByType(paramModel.getType());
        if(dictIdAndType != null){
            throw ApiException.getInstance("标识已存在");
        }

        AppDictEntity appDictEntity = new AppDictEntity();
        appDictEntity.setData(paramModel);
        appDictService.save(appDictEntity);
    }

    /**
     * 编辑
     * @param
     * @return
     */
    @ApiOperation("修改")
    @PostMapping("/edit")
    public void edit(@Validated @RequestBody AppDictEditParamModel paramModel) {
        //校验参数
        AppDictEntity appDictEntity = appDictService.getById(paramModel.getId());
        if(appDictEntity == null){
            throw  new ApiException("数据不存在，请刷新重试");
        }

        AppDictEntity dictIdAndType = appDictService.findByType(paramModel.getType());
        if(dictIdAndType != null && !dictIdAndType.getId().equals(paramModel.getId())){
            throw ApiException.getInstance("标识已存在");
        }

        //方式一：适合单一编辑
        appDictEntity.setData(paramModel);
        appDictService.updateById(appDictEntity);
    }

    @ApiOperation("删除")
    @DeleteMapping("/delByIds/{ids}")
    public void delByIds(@PathVariable String[] ids) {
        appDictService.delByIds(Arrays.asList(ids));
    }
}